import { useQuery } from '@tanstack/react-query';
import { message, Image, Input, Switch, Pagination, Collapse } from 'antd';
import { useEffect, useState } from 'react';
import { useLocation } from 'react-router-dom';

import commonService from '@/api/services/commonService';
import FavIcon from '@/assets/img/collect_off.png';
import FavOnIcon from '@/assets/img/collect_on.png';
import TopImg from '@/assets/img/scene.png';
import SearchImg from '@/assets/img/search.png';
import { CommonButtons } from '@/components/CommonButtons';

const { Panel } = Collapse;

const useHashParams = () => {
  const location = useLocation();
  const [hashParams, setHashParams] = useState<{ [key: string]: string }>({});

  useEffect(() => {
    const { hash } = window.location;
    const query = new URLSearchParams(hash.split('?')[1]);
    const params: { [key: string]: string } = {};
    query.forEach((value, key) => {
      params[key] = value;
    });
    setHashParams(params);
  }, [location]);

  return hashParams;
};

export default function ScenePage() {
  // const [form] = Form.useForm();
  const [list, setList] = useState<any>([]);
  const [query, setQuery] = useState<any>({
    pageSize: 12,
    pageNo: 1,
  });
  const [keyword, setkeyword] = useState('');

  const hashParams = useHashParams();

  useEffect(() => {
    setQuery({ ...query, ...hashParams });
    setkeyword(hashParams.keyword);
  }, [hashParams]);

  useEffect(() => {
    commonService.getCustomApi('/common/designer/getDesignGroup', {}).then((res) => {
      setList(res);
    });
  }, []);

  const doFav = async (item: any) => {
    await commonService.collectApi('collect', { targetId: item.id, type: 2 });
    message.success('收藏成功！');
    refetch();
  };

  const { data = {}, refetch } = useQuery({
    queryKey: ['scene', query],
    queryFn: async () => {
      const params: any = {};
      Object.keys(query).forEach((key) => {
        if (query[key] || query[key] === 0) {
          params[key] = query[key];
        }
      });
      return commonService.getFrontApi('scene', params);
    },
  });
  return (
    <div className="relative left-[50%] ml-[-712px] mt-[40px] flex w-[1424px] flex-col">
      <div>首页 / 场景</div>
      <div className="mb-[80px] mt-[30px] w-[1424px] rounded-[10px]">
        <Image src={TopImg} preview={false} alt="banner" />
      </div>
      <div className="flex justify-between">
        <div className="mr-[52px] flex w-[352px] flex-col gap-[20px]">
          <Input
            className="home-search"
            value={keyword}
            onChange={(e) => setkeyword(e.target.value)}
            placeholder="搜索素材"
            style={{ width: '340px' }}
            suffix={
              <Image
                preview={false}
                onClick={() => {
                  setQuery({ ...query, keyword });
                }}
                className="h-[34px] w-[34px] cursor-pointer"
                src={SearchImg}
              />
            }
          />
          <div className="flex w-full justify-between">
            <div>支持编辑</div>
            <Switch
              value={query.isEdit === 0}
              onChange={(e) => setQuery({ ...query, isEdit: e ? 0 : 1 })}
            />
          </div>
          <div>
            {list.map((item: any) => {
              return (
                <Collapse key={item.id} ghost expandIconPosition="end">
                  <Panel header={item.name} key={item.id}>
                    <div className="flex flex-col gap-[10px]">
                      {item.sonList.map((sub: any) => {
                        return (
                          <div
                            onClick={() => setQuery({ ...query, groupId: sub.id })}
                            key={sub.id}
                            className={[
                              'flex cursor-pointer flex-col gap-[10px] font-[12px]',
                              query.groupId == sub.id
                                ? 'font-weight text-[#FD7901]'
                                : 'text-[#999999]',
                            ].join(' ')}
                          >
                            {sub.name}
                          </div>
                        );
                      })}
                    </div>
                  </Panel>
                </Collapse>
              );
            })}
          </div>
          {/* {list.map((item: any) => {
            return (
              <div
                className={[
                  'cursor-pointer',
                  query.groupId === item.id ? 'font-weight text-[#FD7901]' : '',
                ].join(' ')}
                key={item.id}
                onClick={() => setQuery({ ...query, groupId: item.id })}
              >
                {item.name}
              </div>
            );
          })} */}
        </div>
        <div className="flex-1 flex-col">
          {/** 商品列表 */}
          <div className="flex-start flex flex-wrap gap-[20px]">
            {data.list
              ? data.list.map((item: any) => {
                  return (
                    <div
                      key={item.id}
                      className="relative flex w-[240px] cursor-pointer flex-col bg-[#F2F3F7] leading-[24px]"
                    >
                      <div className="relative h-[220px] w-[100%] overflow-hidden">
                        <Image
                          className="!w-[100%]"
                          preview={false}
                          alt={item.name}
                          src={item.thumb}
                        />
                        <div
                          className="absolute right-[12px] top-[12px] !w-[34px]"
                          onClick={(e) => {
                            e.stopPropagation();
                            doFav(item);
                          }}
                        >
                          <Image src={true ? FavIcon : FavOnIcon} preview={false} alt="fav" />
                        </div>
                      </div>
                      <div className="absolute left-[10px] top-[10px] mt-[4px] rounded-[10px] bg-[rgba(0,0,0,0.2)] px-[10px] text-[20px] leading-[30px]">
                        {item.name}
                        {/* ￥{(item.price / 100).toFixed(2)} */}
                      </div>
                      <CommonButtons good={item} design designTitle="使用该设计" />
                    </div>
                  );
                })
              : ''}
          </div>
          <div className="flex justify-around py-[20px]">
            <Pagination
              current={data.pageNo}
              pageSize={data.pageSize}
              total={data.totalCount}
              onChange={(e) => setQuery({ ...query, pageNo: e })}
              showSizeChanger={false}
            />
          </div>
        </div>
      </div>
    </div>
  );
}
